package org.dut.community.service;

import org.dut.community.util.CommunityConstant;
import org.dut.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class DataService implements CommunityConstant {
    @Autowired
    private RedisTemplate redisTemplate;

    // 日期格式化
    private static final SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");

    public void recordUV(String ip) {
        // 统计UV
        String redisKey = RedisKeyUtil.getUVKey(df.format(new Date()));
        redisTemplate.opsForHyperLogLog().add(redisKey, ip);
    }

    public long calculateUV(Date startDate, Date endDate) {
        if(startDate == null || endDate == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        List<String> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        while(!calendar.getTime().after(endDate)){
            String redisKey = RedisKeyUtil.getUVKey(df.format(calendar.getTime()));
            keyList.add(redisKey);
            calendar.add(Calendar.DATE, 1);
        }
        String redisKey = RedisKeyUtil.getUVKey(df.format(startDate), df.format(endDate));
        redisTemplate.opsForHyperLogLog().union(redisKey, keyList.toArray());

        return redisTemplate.opsForHyperLogLog().size(redisKey);

    }

    public void recordDAU(int userId){
        String redisKey = RedisKeyUtil.getDAUKey(df.format(new Date()));
        redisTemplate.opsForValue().setBit(redisKey, userId, true);
    }

    public long calculateDAU(Date startDate, Date endDate){
        if(startDate == null || endDate == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        List<byte[]> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        while(!calendar.getTime().after(endDate)){
            String redisKey = RedisKeyUtil.getDAUKey(df.format(calendar.getTime()));
            keyList.add(redisKey.getBytes());
            calendar.add(Calendar.DATE, 1);
        }

        return (long)redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                 String redisKey = RedisKeyUtil.getDAUKey(df.format(startDate), df.format(endDate));
                 connection.bitOp(RedisStringCommands.BitOperation.OR, redisKey.getBytes(),
                         keyList.toArray(new byte[0][0]));
                 return connection.bitCount(redisKey.getBytes());
            }
        });
    }

    public List<Long> getUVChartDate(Date startDate,Date endDate){
        List<Long> list = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);

        while(!calendar.getTime().after(endDate)){
            String redisKey = RedisKeyUtil.getUVKey(df.format(calendar.getTime()));
            list.add(redisTemplate.opsForHyperLogLog().size(redisKey));
            calendar.add(Calendar.DATE, 1);
        }
        return list;
    }

    public List<Long> getDAUChartDate(Date startDate,Date endDate){
        List<Long> list = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        while(!calendar.getTime().after(endDate)){
            String redisKey = RedisKeyUtil.getDAUKey(df.format(calendar.getTime()));
            Long dailyCount = (Long) redisTemplate.execute(new RedisCallback<Long>() {
                @Override
                public Long doInRedis(RedisConnection connection) throws DataAccessException {
                    return connection.bitCount(redisKey.getBytes());
                }
            });
            if(dailyCount == null){
                dailyCount = 0L;
            }
            list.add(dailyCount);
            calendar.add(Calendar.DATE, 1);
        }
        return list;
    }

}
